package com.wangtao.firstapp.fragments.communityfragment;

import android.content.Intent;
import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.jcodecraeer.xrecyclerview.ProgressStyle;
import com.jcodecraeer.xrecyclerview.XRecyclerView;
import com.wangtao.firstapp.R;
import com.wangtao.firstapp.activity.CategoryClassActivity;
import com.wangtao.firstapp.activity.HotRecommendActivity;
import com.wangtao.firstapp.adapters.MyClassAdapter;
import com.wangtao.firstapp.adapters.MyHotCommendAdapter;
import com.wangtao.firstapp.custom.MyGridView;
import com.wangtao.firstapp.inter.OnRVItemClickListener;
import com.wangtao.firstapp.inter.OnRVItemLongClickListener;
import com.wangtao.firstapp.modles.CategoryPictures;
import com.wangtao.firstapp.modles.CommunityHotRecommend;
import com.wangtao.firstapp.utils.HttpUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * 晒单页面
 * Created by lanouhn on 16/8/24.
 */
public class CommunityShowFragment extends Fragment implements OnRVItemClickListener, OnRVItemLongClickListener {
    private CategoryPictures pictures;// 晒单页面下分类模块的RecyclerView的图片实体类
    //private CategoryRVAdapter rvadapter;// 晒单页面下分类模块的RecyclerView的适配器  适配器已废弃
    private List<CommunityHotRecommend.DataBean> recommends = new ArrayList<>();// 晒单页面下热门推荐模块图片的实体类
    private List<CommunityHotRecommend.DataBean> datas = new ArrayList<>();
    private MyGridView mygridview_category;
    // private MyGridView mygridview_rec;
    private XRecyclerView xrecyclerview_rec;
    private MyClassAdapter myClassAdapter;
    private MyHotCommendAdapter myHotCommendAdapter;
    private SwipeRefreshLayout swiperefreshlayout_show;
    int page = 0;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = LayoutInflater.from(getActivity()).inflate(R.layout.communityshowfragment, null);
        mygridview_category = (MyGridView) view.findViewById(R.id.mygridview_category);
        xrecyclerview_rec = (XRecyclerView) view.findViewById(R.id.xrecyclerview_rec);
        // swiperefreshlayout_show = (SwipeRefreshLayout) view.findViewById(R.id.swiperefreshlayout_show);
        //scrollview_show.setFocusable(false);

        GridLayoutManager gridLayoutManager = new GridLayoutManager(getActivity(), 3);
        xrecyclerview_rec.setLayoutManager(gridLayoutManager);


        xrecyclerview_rec.setRefreshProgressStyle(ProgressStyle.BallSpinFadeLoader);
        xrecyclerview_rec.setArrowImageView(R.drawable.ic_loading_rotate);
        xrecyclerview_rec.setLoadingListener(new XRecyclerView.LoadingListener() {
            @Override
            public void onRefresh() {
                page = 0;
                getHotData();
            }

            @Override
            public void onLoadMore() {
                page++;
                getHotData();
            }
        });


        initEvent();
        getClassData();
        getHotData();
        // SwipeToRefresh();
        return view;
    }

    private void getClassData() {
        // 获取分类模块下的图片
        String url = "http://open4.bantangapp.com/community/post/index";
        String params = "app_id=com.jzyd.BanTang&client_id=bt_app_android&client_secret=ffcda7a1c4ff338e05c42e7972ba7b8d&track_user_id=2559956&oauth_token=6beffa8c92276d19d3c23acb596024e6&track_deviceid=866962021116243&track_device_info=m1+note&channel_name=ppzhushuo&app_installtime=1471923362&app_versions=5.8.6&os_versions=5.1&screensize=1080&v=18";

        try {
            HttpUtils.doPostAsyn(url, params, new HttpUtils.CallBack() {
                @Override
                public void onRequestComplete(String result) {
                    Gson gson = new Gson();
                    pictures = gson.fromJson(result, CategoryPictures.class);
                    if (pictures.getData().getCategory_list().size() > 0) {
                        handler.sendEmptyMessage(1);
                    } else {
                        handler.sendEmptyMessage(0);
                    }
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void getHotData() {
        // 热门推荐
        String url1 = "http://open4.bantangapp.com/community/post/hotRecommend";
        String params1 = "app_id=com.jzyd.BanTang&client_id=bt_app_android&client_secret=ffcda7a1c4ff338e05c42e7972ba7b8d&track_user_id=2559956&oauth_token=6beffa8c92276d19d3c23acb596024e6&track_deviceid=866962021116243&track_device_info=m1+note&channel_name=ppzhushuo&app_installtime=1471923362&app_versions=5.8.6&os_versions=5.1&screensize=1080&v=18&page=" + page + "&pagesize=18&id=1&type_id=1";
        try {
            HttpUtils.doPostAsyn(url1, params1, new HttpUtils.CallBack() {
                @Override
                public void onRequestComplete(String result) {
                    Gson gson1 = new Gson();
                    datas = gson1.fromJson(result, CommunityHotRecommend.class).getData();
                    if (datas.size() > 0) {
                        handler.sendEmptyMessage(2);
                    } else {
                        // handler.sendEmptyMessage(0);
                    }
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 0:
                    //  Toast.makeText(getActivity(), "网络访问失败", Toast.LENGTH_SHORT).show();
                    break;
                case 1:
                    myClassAdapter = new MyClassAdapter(getActivity(), pictures);
                    mygridview_category.setAdapter(myClassAdapter);
                    break;
                case 2:
                    if (page == 0) {
                        recommends.clear();
                        recommends.addAll(datas);
                        myHotCommendAdapter = new MyHotCommendAdapter(getActivity(), recommends);
                        xrecyclerview_rec.setAdapter(myHotCommendAdapter);
                        xrecyclerview_rec.refreshComplete();
                        datas.clear();
                    } else {
                        recommends.addAll(datas);
                        myHotCommendAdapter.notifyDataSetChanged();
                        xrecyclerview_rec.loadMoreComplete();
                        datas.clear();
                    }
                    myHotCommendAdapter.setClickListener(CommunityShowFragment.this);
                    myHotCommendAdapter.setLongClickListener(CommunityShowFragment.this);
                    break;
            }
        }
    };

    // 晒单下分类item点击事件
    private void initEvent() {
        mygridview_category.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                String addid = "" + pictures.getData().getCategory_list().get(position).getId();
                Intent intent = new Intent(getActivity(), CategoryClassActivity.class);
                intent.putExtra("id", addid);
                startActivity(intent);
            }
        });
    }

    // 下拉刷新
    private void SwipeToRefresh() {
        swiperefreshlayout_show.setColorSchemeColors(Color.CYAN, Color.BLUE, Color.GREEN, Color.YELLOW);
        swiperefreshlayout_show.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                swiperefreshlayout_show.setRefreshing(true);
                (new Handler()).postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        swiperefreshlayout_show.setRefreshing(false);

                        myHotCommendAdapter.notifyDataSetChanged();
                    }
                }, 3000);
            }
        });
    }

    // 晒单下热门推荐item点击事件
    @Override
    public void OnRVItemClickListener(int position) {
        String addid = "" + recommends.get(position).getId();
        Intent intent = new Intent(getActivity(), HotRecommendActivity.class);
        Bundle bundle = new Bundle();
        bundle.putInt("position", position);
        bundle.putString("addid", addid);
        intent.putExtras(bundle);
        startActivity(intent);
    }

    // 晒单下热门推荐item点击事件
    @Override
    public void OnRVItemLongClickListener(int position) {
        String addid = "" + recommends.get(position).getId();
        Intent intent = new Intent(getActivity(), HotRecommendActivity.class);
        Bundle bundle = new Bundle();
        bundle.putInt("position", position);
        bundle.putString("addid", addid);
        intent.putExtras(bundle);
        startActivity(intent);
    }
}
